#include "delete_file_command.h"
#include "service/backend_service.h"
#include "../database/database_manager.h"
#include "command_executor.h"
#include <QDebug>
#include <QUrl>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>

DeleteFileCommand::DeleteFileCommand(QObject *parent)
    : BaseCommand(parent)
    , m_pendingFileId("")
{
}

DeleteFileCommand::~DeleteFileCommand()
{
}

void DeleteFileCommand::setNetworkAccessManager(QNetworkAccessManager *networkManager)
{
    // 如果之前已经设置了 networkManager，先断开旧的连接
    if (m_networkManager) {
        disconnect(m_networkManager, &QNetworkAccessManager::finished,
                   this, &DeleteFileCommand::handleDeleteFileResponse);
    }
    
    BaseCommand::setNetworkAccessManager(networkManager);
    
    // 连接网络请求完成信号
    if (m_networkManager) {
        connect(m_networkManager, &QNetworkAccessManager::finished,
                this, &DeleteFileCommand::handleDeleteFileResponse);
    }
}

bool DeleteFileCommand::execute(const QString &fileId)
{
    if (!isValid()) {
        qDebug() << "DeleteFileCommand: BackendService 或 QNetworkAccessManager 未设置";
        emit deleteFileCompleted(-1, "BackendService 或 QNetworkAccessManager 未设置");
        return false;
    }
    
    if (fileId.isEmpty()) {
        qDebug() << "DeleteFileCommand: 文件ID为空";
        emit deleteFileCompleted(-1, "文件ID为空");
        return false;
    }
    
    // 检查是否有accessToken，如果没有则先获取
    if (!ensureAccessToken()) {
        // 如果没有选中的公司ID，无法获取accessToken
        if (!m_backendService || m_backendService->loadSelectedCompanyId().isEmpty()) {
            qDebug() << "DeleteFileCommand: 没有选中的公司ID，无法获取accessToken";
            emit deleteFileCompleted(-1, "没有选中的公司ID，无法获取accessToken");
            return false;
        }
        // 正在获取 token，保存待处理的文件ID
        m_pendingFileId = fileId;
        return true; // 返回true表示已发起获取token的请求
    }
    
    // 获取 accessToken
    QString accessToken = CommandExecutor::getAccessToken();
    
    // 获取 baseUrl
    QString baseUrl = getBaseUrl();
    
    // 构建请求URL
    QString url = buildRequestUrl(baseUrl, fileId);
    
    qDebug() << "DeleteFileCommand: 开始删除文件，URL:" << url;
    qDebug() << "DeleteFileCommand: 文件ID:" << fileId;
    qDebug() << "DeleteFileCommand: 当前accessToken:" << accessToken;
    
    // 创建网络请求
    QNetworkRequest request = createRequest(url, "DELETE", "DeleteFileCommand/1.0");
    
    // 添加token到请求头
    addTokenToRequest(request, accessToken);
    
    // 验证accessToken是否已添加到请求头
    QByteArray accessTokenHeader = request.rawHeader("accessToken");
    if (accessTokenHeader.isEmpty()) {
        qDebug() << "DeleteFileCommand: 警告：accessToken未添加到请求头，尝试手动添加";
        request.setRawHeader("accessToken", accessToken.toUtf8());
    } else {
        qDebug() << "DeleteFileCommand: 确认accessToken已添加到请求头:" << accessTokenHeader;
    }
    
    // 发送DELETE请求
    QNetworkReply *reply = m_networkManager->sendCustomRequest(request, "POST", QByteArray());
    qDebug() << "DeleteFileCommand: 发送删除文件请求，reply对象:" << reply;
    
    if (!reply) {
        qDebug() << "DeleteFileCommand: 创建删除文件请求失败";
        emit deleteFileCompleted(-1, "创建网络请求失败");
        return false;
    }
    
    // 设置用户数据，用于识别请求类型
    reply->setProperty("requestType", "deleteFile");
    
    // 保存文件ID到reply属性中
    reply->setProperty("fileId", fileId);
    
    return true;
}

void DeleteFileCommand::handleDeleteFileResponse(QNetworkReply *reply)
{
    // 检查对象是否仍然有效（可能在信号排队期间被销毁）
    if (!isValid()) {
        qDebug() << "DeleteFileCommand: 对象已被销毁，忽略响应";
        if (reply) {
            reply->deleteLater();
        }
        return;
    }
    
    if (!reply) {
        qDebug() << "DeleteFileCommand: 删除文件响应为空";
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit deleteFileCompleted(-1, "删除响应为空");
        }
        return;
    }
    
    QString requestType = reply->property("requestType").toString();
    if (requestType != "deleteFile") {
        // 不是删除文件请求，忽略
        reply->deleteLater();
        return;
    }
    
    qDebug() << "DeleteFileCommand: 处理删除文件响应，错误:" << reply->error();
    
    if (reply->error() == QNetworkReply::NoError) {
        // 删除文件成功
        QByteArray data = reply->readAll();
        qDebug() << "DeleteFileCommand: 删除文件响应，数据大小:" << data.size() << "字节";
        qDebug() << "DeleteFileCommand: 删除文件响应数据:" << data;
        
        // 解析JSON响应
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
        
        // 再次检查对象是否仍然有效
        if (!isValid()) {
            qDebug() << "DeleteFileCommand: 对象已被销毁，忽略响应解析";
            reply->deleteLater();
            return;
        }
        
        if (parseError.error != QJsonParseError::NoError) {
            qDebug() << "DeleteFileCommand: 删除文件JSON解析错误:" << parseError.errorString();
            // 只有在对象仍然有效时才发送信号
            if (isValid()) {
                emit deleteFileCompleted(-1, "JSON解析失败: " + parseError.errorString());
            }
            reply->deleteLater();
            return;
        }
        
        if (!doc.isObject()) {
            qDebug() << "DeleteFileCommand: 删除文件响应不是有效的JSON对象";
            // 只有在对象仍然有效时才发送信号
            if (isValid()) {
                emit deleteFileCompleted(-1, "响应格式错误");
            }
            reply->deleteLater();
            return;
        }
        
        // 最后一次检查对象是否仍然有效
        if (!isValid()) {
            qDebug() << "DeleteFileCommand: 对象已被销毁，忽略响应解析";
            reply->deleteLater();
            return;
        }
        
        QJsonObject response = doc.object();
        // 从reply属性中获取文件ID
        QString fileId = reply->property("fileId").toString();
        
        parseDeleteFileResponse(response, fileId);
    } else {
        qDebug() << "DeleteFileCommand: 删除文件失败:" << reply->errorString();
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit deleteFileCompleted(reply->error(), "删除失败: " + reply->errorString());
        }
    }
    
    reply->deleteLater();
}

void DeleteFileCommand::parseDeleteFileResponse(const QJsonObject &response, const QString &fileId)
{
    // 检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "DeleteFileCommand: 对象已被销毁，忽略响应解析";
        return;
    }
    
    qDebug() << "DeleteFileCommand: 解析删除文件响应";
    
    int errcode = response["errcode"].toInt();
    QString errmsg = response["errmsg"].toString();
    bool data = response["data"].toBool();
    
    if (errcode == 0) {
        qDebug() << "DeleteFileCommand: 删除文件成功:" << errmsg << "data:" << data;
        
        // 删除成功后，同步删除 kms_file 表记录
        if (m_databaseManager && !fileId.isEmpty()) {
            bool deleted = m_databaseManager->deleteFile(fileId);
            if (deleted) {
                qDebug() << "DeleteFileCommand: 成功删除数据库中的文件记录，文件ID:" << fileId;
            } else {
                qDebug() << "DeleteFileCommand: 删除数据库中的文件记录失败或记录不存在，文件ID:" << fileId;
            }
        } else {
            if (!m_databaseManager) {
                qDebug() << "DeleteFileCommand: 数据库管理器未设置，无法删除文件记录";
            }
            if (fileId.isEmpty()) {
                qDebug() << "DeleteFileCommand: 文件ID为空，无法删除文件记录";
            }
        }
        
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit deleteFileCompleted(0, errmsg);
        }
    } else {
        qDebug() << "DeleteFileCommand: 删除文件失败:" << errmsg;
        // 只有在对象仍然有效时才发送信号
        if (isValid()) {
            emit deleteFileCompleted(errcode, errmsg);
        }
    }
}

QString DeleteFileCommand::buildRequestUrl(const QString &baseUrl, const QString &fileId)
{
    return baseUrl + "/kms/api/kms/sync/files/" + fileId;
}

